package com.econ.powercloud.ems.dal.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 填充公共字段
 *
 * @author chenxiaoqi
 * @since 2020/08/06
 */
public class AutoFillMetaObjectHandler implements MetaObjectHandler {

    private static final String FIELD_DELETE_FLAG = "deleteFlag";

    @Override
    public void insertFill(MetaObject metaObject) {
        Object originalObject = metaObject.getOriginalObject();
        Set<String> fieldNames = this.getAllFields(originalObject.getClass());
        if (fieldNames.contains(FIELD_DELETE_FLAG)) {
            setFieldValByName(FIELD_DELETE_FLAG, 0, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

    }

    private Set<String> getAllFields(Class<?> entityClass) {
        Field[] declaredFields = entityClass.getDeclaredFields();
        Set<String> fieldNames = Arrays.stream(declaredFields).map(Field::getName).collect(Collectors.toSet());

        Class<?> superclass = entityClass.getSuperclass();
        if (superclass.equals(Object.class)) {
            return fieldNames;
        }
        fieldNames.addAll(this.getAllFields(superclass));
        return fieldNames;
    }
}